package br.great.functionalCore;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import br.great.beans.Photo;
import br.great.beans.Point;
import br.great.beans.TimeSunRaiseSet;
import br.great.config.PhotomapConstants;

/**
 * PhotoMap
 * Copyright (c) 2007-2008 STEAMER - LIG, All rights reserved.
 */
/**
 * @author Developpement of PhotoMap
 */
public class EarthTools_SunRiseSet {

    /** method description
     * @param var signification
     * @exception exception class name
     * @return return_value return signification
     * @see package.class#member label
     */
    private static String url = "http://www.earthtools.org/";

    public ArrayList<Time> findSunRiseSet(Point center, Date date) {
        ArrayList<Time> alt = new ArrayList<Time>();
        try {
            // URL + /<latitude>/<longitude>/<day>/<month>/<timezone>/<dst>
            String timezone = "timezone";
            String sunRiseSet = "sun";
            String url_timezone = url + timezone;
            String centerS = "/" + center.getLatitude() + "/" + center.getLongitude();
            url_timezone = url_timezone + centerS;

            // connect with the web service
            URLConnection conn = new URL(url_timezone).openConnection();
            // parser le text we receve
            SAXBuilder parser = new SAXBuilder();
            Document doc = parser.build(conn.getInputStream());
            // get the element of offset
            Element root = doc.getRootElement();
            Element elementOffset = root.getChild("offset");
            // get the value of offset
            int offset = Integer.parseInt(elementOffset.getText());
            TimeSunRaiseSet tsrs = new TimeSunRaiseSet();
            tsrs.setTimeZone(offset);

            String url_sunRS = url + sunRiseSet;
            url_sunRS = url_sunRS + centerS + "/" + date.getDay() + "/" + date.getMonth() + "/" + offset + "/1";
            // connect with the web service
            URLConnection connSun = new URL(url_sunRS).openConnection();
            // parser le text we receve
            SAXBuilder parserSun = new SAXBuilder();
            Document docSun = parserSun.build(connSun.getInputStream());
            Element rootSun = docSun.getRootElement();
            Element morning = rootSun.getChild("morning");
            Element evening = rootSun.getChild("evening");

            alt.add(Time.valueOf(morning.getChild("twilight").getChildText("astronomical")));
            alt.add(Time.valueOf(morning.getChildText("sunrise")));
            alt.add(Time.valueOf(evening.getChildText("sunset")));
            alt.add(Time.valueOf(evening.getChild("twilight").getChildText("astronomical")));
        } catch (JDOMException ex) {
            Logger.getLogger(EarthTools_SunRiseSet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(EarthTools_SunRiseSet.class.getName()).log(Level.SEVERE, null, ex);
        }
        return alt;
    }

    public ArrayList<Calendar> AddTimeInCalendars(Calendar cal, String[] sa) {
        ArrayList<Calendar> al = new ArrayList<Calendar>();
        int YEAR = cal.get(Calendar.YEAR);
        int MONTH = cal.get(Calendar.MONTH);
        int DAY = cal.get(Calendar.DAY_OF_MONTH);
        for (int i = 0; i < sa.length; i++) {
            String[] saTime = sa[i].split(":");
            Calendar calWithTime = Calendar.getInstance();
            calWithTime.set(YEAR, MONTH, DAY, Integer.parseInt(saTime[0]), Integer.parseInt(saTime[1]), Integer.parseInt(saTime[2]));
            al.add(calWithTime);
        }
        return al;
    }

    public void getPartOfDay_Photos(Photo p) {
        java.text.SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmss");
        int beforeMorning = Integer.parseInt(dateFormat.format(Time.valueOf("06:00:00")));
        int midi = Integer.parseInt(dateFormat.format(Time.valueOf("12:00:00")));

        int Afternoon = Integer.parseInt(dateFormat.format(Time.valueOf("17:00:00")));
        int beforeNight = Integer.parseInt(dateFormat.format(Time.valueOf("21:00:00")));
        int dayEnd = Integer.parseInt(dateFormat.format(Time.valueOf("23:59:59")));

//        for (int i = 0; i < photos.size(); i++) {
//            Photo p = photos.get(i);
            String partOfDay = null;
            if (p.getDateTime() != null) {
                int date = Integer.parseInt(dateFormat.format(p.getDateTime()));
                if (date <= beforeMorning) {
                    partOfDay = PhotomapConstants.NIGHT;
                } else if (date < midi) {
                    partOfDay = PhotomapConstants.MORNING;
                } else if (date < Afternoon) {
                    partOfDay = PhotomapConstants.AFTERNOON;
                } else if (date < beforeNight) {
                    partOfDay = PhotomapConstants.EVENING;
                } else if (date < dayEnd) {
                    partOfDay = PhotomapConstants.NIGHT;
                }
//            }
        }
        p.setPartOfDay(partOfDay);
    }

    public void getLightStatusPhotos(Photo p, Date photoDate) {
//        Calendar cal = Calendar.getInstance();
//        for (int i = 0; i < photos.size(); i++) {
//            Photo p = photos.get(i);
//            cal.setTime(new Date(0,1,2));
            String lightStatus = null;
            try{
            ArrayList al = findSunRiseSet(p.getCoor(), photoDate);
            java.text.SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmss");
            int beforeSunrise = Integer.parseInt(dateFormat.format((Date) al.get(0)));
            int afterSunrise = Integer.parseInt(dateFormat.format((Date) al.get(1)));
//        int midi = Integer.parseInt(dateFormat.format(Time.valueOf("12:00:00")));
            int beforeSunset = Integer.parseInt(dateFormat.format((Date) al.get(2)));
            int afterSunset = Integer.parseInt(dateFormat.format((Date) al.get(3)));
            int dayEnd = Integer.parseInt(dateFormat.format(Time.valueOf("23:59:59")));

            
            if (p.getDateTime() != null) {
                int date = Integer.parseInt(dateFormat.format(p.getDateTime()));
                if (date <= beforeSunrise) {
                    lightStatus = PhotomapConstants.NIGHT;
                } else if (date < afterSunrise) {
                    lightStatus = PhotomapConstants.SUNRISE;
                } else if (date < beforeSunset) {
                    lightStatus = PhotomapConstants.DAY;
                } else if (date < afterSunset) {
                    lightStatus = PhotomapConstants.SUNSET;
                } else if (date < dayEnd) {
                    lightStatus = PhotomapConstants.NIGHT;
                }
              }
            }catch(Exception e){            
                lightStatus = PhotomapConstants.DAY;
            }
        //}
        p.setLightStatus(lightStatus);
    }
//    public static void main(String[] args){
//        EarthTools_SunRiseSet esrs = new EarthTools_SunRiseSet();
//        Point p = new Point();
//        p.setLatitude(45);
//        p.setLongitude(12);
//        
//        Calendar cal = Calendar.getInstance();
//        cal.set(0,2,3);
//        ArrayList al = esrs.findSunRiseSet(p, cal);
//        for (int i=0; i<al.size(); i++){
//             System.out.println(al.get(i).toString());
//        }
//       
//    }
}
